
import {
    actionTypes
} from "./createStore";
import {
    Dispatch
} from "./applyMiddleware";
import { stateType } from "../..";

export interface ActionCreator<A = actionTypes> {
    (...args: any[]): A;
}
export interface ActionCreatorsMapObject<A = any> {
    [key: string]: ActionCreator<A>;
}
function bindActionCreator(actionCreator: ActionCreator, dispatch: Dispatch) {
    return function (this:any) {
        return dispatch(actionCreator.apply(this, arguments))
    }
}

export default function bindActionCreators(actionCreators: ActionCreator | ActionCreatorsMapObject, dispatch: Dispatch) {
    if (typeof actionCreators === 'function') {
        return bindActionCreator(actionCreators, dispatch)
    }
    const keys = Object.keys(actionCreators)
    const boundActionCreators:{
        [key:string]:(this:any)=>stateType
    } = {}
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i]
      const actionCreator = actionCreators[key]
      if (typeof actionCreator === 'function') {
        boundActionCreators[key] = bindActionCreator(actionCreator, dispatch) 
      }
    }
    return boundActionCreators
}